/**
 * @author zhouheng
 * @date 2022年03月08日 22:25
 */

package com.atguigu.gulimall.gulimallauth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthContant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.gulimallauth.feign.ThirdPartyFeignService;
import com.atguigu.gulimall.gulimallauth.feign.MemberFeignService;
import com.atguigu.gulimall.gulimallauth.vo.UserLoginVo;
import com.atguigu.gulimall.gulimallauth.vo.UserRegisterVo;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Slf4j
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @RequestMapping(value = {"/login.html", "/"})
    public String login(HttpSession session) {
        Object attribute = session.getAttribute(AuthContant.LOGIN_USER);
        if (attribute == null) {
            System.out.println("attribute:"+attribute);
            return "login";
        }

        System.out.println("已登陆过，重定向到首页");
        return "redirect:http://gulimall.com";
    }

    @PostMapping("/login") // auth
    public String login(UserLoginVo userLoginVo, // from表单里带过来的
        RedirectAttributes redirectAttributes,
        HttpSession session){
        // 远程登录
        R r = memberFeignService.login(userLoginVo);
        if(r.getCode() == 0){
            // 登录成功
            MemberRespVo respVo = r.getData("data", new TypeReference<MemberRespVo>() {});
            // 放入session
            session.setAttribute(AuthContant.LOGIN_USER, respVo);//loginUser
            log.info("\n欢迎 [" + respVo.getUsername() + "] 登录");
            return "redirect:http://gulimall.com";
        }else {
            HashMap<String, String> error = new HashMap<>();
            // 获取错误信息
            error.put("msg", r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors", error);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }

    /** 接收到一个手机号，在此处生成验证码和缓存，然后转给第三方服务让他给手机发验证按
     * */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendMsm(@RequestParam("phone") String phone) {
        String cacheKey = AuthContant.SMS_CODE_CACHE_PREFIX + phone;
        String smsCode = stringRedisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotBlank(smsCode)) {
            String curTime = smsCode.split("_")[1];
            // 比较时间 是否超过60s 60s内不能重复发送短信
            if (System.currentTimeMillis() - Long.parseLong(curTime) < 60 * 1000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        // 生成缓存记录
        smsCode = UUID.randomUUID().toString().substring(0, 6);
        stringRedisTemplate.opsForValue().set(cacheKey, smsCode + "_" +System.currentTimeMillis(), 10, TimeUnit.MINUTES);
        // 调用远程服务发送短信验证码
        try {
            return thirdPartyFeignService.sendCode(phone, smsCode);
        } catch (Exception e) {
            log.warn("远程调用不知名错误 [无需解决]");
        }

        return R.ok();
    }

    /**
     * TODO 1. 分布式下的session问题
	 * 校验
	 * RedirectAttributes redirectAttributes ： 模拟重定向带上数据
	 */
    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo,
        BindingResult result,
        RedirectAttributes redirectAttributes){

        if(result.hasErrors()){

            // 将错误属性与错误信息一一封装
            Map<String, String> errors = result.getFieldErrors().stream().collect(
                Collectors.toMap(FieldError::getField, fieldError -> fieldError.getDefaultMessage()));
            // addFlashAttribute 这个数据只取一次
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

        // 开始注册 调用远程服务
        // 1.校验验证码
        String code = userRegisterVo.getCode();
        String redis_code = stringRedisTemplate.opsForValue().get(AuthContant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());

        if(!org.springframework.util.StringUtils.isEmpty(redis_code)){
            // 验证码通过
            if(code.equals(redis_code.split("_")[0])){
                // 删除验证码
                stringRedisTemplate.delete(AuthContant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone());
                // 调用远程服务进行注册
                R r = memberFeignService.register(userRegisterVo);
                if(r.getCode() == 0){
                    // 注册成功，去登录
                    return "redirect:http://auth.gulimall.com/login.html";
                }else{
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    // 数据只需要取一次
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else{
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                // addFlashAttribute 这个数据只取一次
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            // addFlashAttribute 这个数据只取一次
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }
}
